package com.xb.cloud.product.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.xb.cloud.common.client.bo.PageBo;
import com.xb.cloud.common.constant.DbConstants;
import com.xb.cloud.common.model.PageParam;
import com.xb.cloud.common.redis.CacheUtil;
import com.xb.cloud.common.util.BeanUtils;
import com.xb.cloud.common.util.StringUtils;
import com.xb.cloud.product.category.service.client.CategoryTreeService;
import com.xb.cloud.product.category.service.client.CategoryTreesRelatedType;
import com.xb.cloud.product.category.service.client.bo.CategoryTreesBO;
import com.xb.cloud.product.category.service.client.bo.SkuRequestBO;
import com.xb.cloud.product.merchant.inner.service.ShopNavigationGroupInnerService;
import com.xb.cloud.product.merchant.service.client.ProductMongoService;
import com.xb.cloud.product.merchant.service.client.ShopService;
import com.xb.cloud.product.merchant.service.client.bo.ProductBo;
import com.xb.cloud.product.merchant.service.client.bo.ProductMongoBo;
import com.xb.cloud.product.merchant.service.client.bo.ProductShopSeriesMongoBo;
import com.xb.cloud.product.merchant.service.client.bo.ProductSkuBo;
import com.xb.cloud.product.merchant.service.client.bo.ShopBo;
import com.xb.cloud.product.merchant.service.client.bo.ShopNavigationGroupBo;
import com.xb.cloud.product.merchant.service.client.bo.ShopSkuBo;
import com.xb.cloud.product.service.business.model.ProductSku;
import com.xb.cloud.product.service.business.model.ProductSkuExample;
import com.xb.cloud.product.service.business.model.ProductSkuExamplePaged;
import com.xb.cloud.product.service.business.model.ProductSkuExtDescription;
import com.xb.cloud.product.service.business.model.ProductSkuExtDescriptionExample;
import com.xb.cloud.product.service.business.model.ProductSkuExtPic;
import com.xb.cloud.product.service.business.model.ProductSkuExtPicExample;
import com.xb.cloud.product.service.business.model.ProductSkuPrice;
import com.xb.cloud.product.service.business.model.ProductSkuPriceExample;
import com.xb.cloud.product.service.business.model.PromotionSku;
import com.xb.cloud.product.service.business.model.PromotionSkuExample;
import com.xb.cloud.product.service.business.model.RecommendSku;
import com.xb.cloud.product.service.business.model.RecommendSkuExample;
import com.xb.cloud.product.service.business.model.SkuPic;
import com.xb.cloud.product.service.business.model.SkuPicExample;
import com.xb.cloud.product.service.business.model.SkuPicExample.Criteria;
import com.xb.cloud.product.service.business.model.mapper.ProductSkuExtDescriptionMapper;
import com.xb.cloud.product.service.business.model.mapper.ProductSkuExtPicMapper;
import com.xb.cloud.product.service.business.model.mapper.ProductSkuMapper;
import com.xb.cloud.product.service.business.model.mapper.ProductSkuPriceMapper;
import com.xb.cloud.product.service.business.model.mapper.PromotionSkuMapper;
import com.xb.cloud.product.service.business.model.mapper.RecommendSkuMapper;
import com.xb.cloud.product.service.business.model.mapper.SkuPicMapper;
import com.xb.cloud.product.service.client.BaseProductConstant;
import com.xb.cloud.product.service.client.ProductService;
import com.xb.cloud.product.service.client.SkuService;
import com.xb.cloud.product.service.client.bo.HomePageRecommendSku;
import com.xb.cloud.product.service.client.bo.ProductDescriptionBo;
import com.xb.cloud.product.service.client.bo.ProductSkuPriceBo;
import com.xb.cloud.product.service.client.bo.SkuBO;
import com.xb.cloud.product.service.client.bo.SkuDetailBO;
import com.xb.cloud.service.client.ServiceReturnCodes;
import com.xb.cloud.service.client.ServiceReturnInfo;
import com.xb.cloud.service.client.ServiceReturnUtils;

/**
 * 
 * @ClassName: SkuServiceImpl
 * @Description:SKU 相关的操作
 * @author: 鲜备科技
 * @date: 2017年12月21日 上午9:54:50
 * 
 * @Copyright: 2017 www.xianbeitech.com Inc. All rights reserved.
 *O
 */
@Service
public class SkuServiceImpl implements SkuService {
	private static final long GROUP_ALL = 0L;
	@Resource
	SkuPicMapper skuPicMapper;
	@Resource
	PromotionSkuMapper promotionSkuMapper;
	@Resource
	ProductSkuMapper productSkuMapper;
	@Resource
	RecommendSkuMapper productSkuRecommendMapper;
	@Resource
	ProductSkuPriceMapper productSkuPriceMapper;
	@Autowired
	private ProductMongoService productMongoService;
	@Autowired
	ProductService productService;
	@Autowired
	ShopService shopService;
	@Resource
	ProductSkuExtDescriptionMapper productSkuExtDescriptionMapper;
	@Resource
	ProductSkuExtPicMapper productSkuExtPicMapper;
	
	
	
	@Resource
	CategoryTreeService categoryTreeService;
	
	@Resource
	private ShopNavigationGroupInnerService shopNavigationGroupInnerService;

	/*@Override
	public String getSKUDefaultPicURL(long sku_ID) {
		SkuPicExample example = new SkuPicExample();
		Criteria criteria = example.createCriteria();
		criteria.andSkuIdEqualTo(sku_ID);
		byte isDefault = 1;
		criteria.andIsDefaultEqualTo(isDefault);
		List<SkuPic> skuPicList = skuPicMapper.selectByExample(example);
		for (SkuPic skuPic : skuPicList) {
			return skuPic.getPicUrl();
		}
		return null;
	}
*/
	@Override
	public List<HomePageRecommendSku> getPromotionSkuByCategory(long category_id) {
		PromotionSkuExample example = new PromotionSkuExample();
		com.xb.cloud.product.service.business.model.PromotionSkuExample.Criteria criteria = example.createCriteria();
		criteria.andPromotionCategoryIdEqualTo(category_id).andIsDeletedEqualTo((byte) 0);
		example.setOrderByClause("sort asc");
		List<HomePageRecommendSku> homePageRecommendSKUPOs = new ArrayList<HomePageRecommendSku>();
		List<PromotionSku> skuList = promotionSkuMapper.selectByExample(example);
		int index = 0;
		for (PromotionSku promotionSku : skuList) {
			HomePageRecommendSku homePageRecommendSKUPO = new HomePageRecommendSku();
			Long skuId = promotionSku.getSkuId();
			homePageRecommendSKUPO.setId(skuId);
			homePageRecommendSKUPO.setIndex(index);

			ProductSku productSku = productSkuMapper.selectByPrimaryKey(skuId);
			homePageRecommendSKUPO.setDefaultPicURL(productService.getProductDefaultPicURL(productSku.getProductId()));
			homePageRecommendSKUPO.setMerchantId(productSku.getMerchantId());
			homePageRecommendSKUPO.setShopId(productSku.getShopId());
			homePageRecommendSKUPO.setSkuNameCn(productSku.getSkuNameCn());
			homePageRecommendSKUPO.setProductId(productSku.getProductId());
			homePageRecommendSKUPO.setUnit(productSku.getSkuUnit());

			//String specification = productService.getSpecificationByID(productSku.getProductId());
			ProductSkuPriceBo priceBo = this.getSKUPriceBySkuId(skuId);
			if(priceBo != null) {
				homePageRecommendSKUPO.setPrice(priceBo.getPriceSale());
				homePageRecommendSKUPO.setPriceMarket(priceBo.getPriceMarket());
			} else {
				continue;
			}
			

			index = index + 1;
			homePageRecommendSKUPOs.add(homePageRecommendSKUPO);
		}
		return homePageRecommendSKUPOs;
	}

	
	@Override
	public List<ShopSkuBo> getShopSkuListBySkuIds(List<Long> skuIds) {
		return productSkuMapper.getShopSkuListBySkuIds(skuIds);
	}
	
	
	/**
	 * 
	 * <p>
	 * Title: getProductListByProduct
	 * </p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param companyID
	 * @param frontCategoryID
	 * @return
	 * @see com.xb.cloud.product.service.client.ProductService#getProductListByProduct(long,
	 *      long)
	 */
	@Override
	public ServiceReturnInfo getSkuByFrontCategoryList(SkuRequestBO requestInfo) {
		ServiceReturnInfo categoryInfo = categoryTreeService.getCategoryTreeByIDs(requestInfo.getCategoryList());
		if (ServiceReturnUtils.isSuccess(categoryInfo)) {
			List<CategoryTreesBO> categoryTreesBOs = (List<CategoryTreesBO>) categoryInfo.getData();
			//后台类目列表
			List<CategoryTreesBO> categoryLeafBOs4BackendCatgeory = new ArrayList<CategoryTreesBO>();
			categoryClassifier(categoryTreesBOs, categoryLeafBOs4BackendCatgeory);

			List<SkuBO> skuList = getSkuByBackendCategoryList(categoryLeafBOs4BackendCatgeory, requestInfo);

			return ServiceReturnUtils.success(skuList);
		} else {
			return ServiceReturnUtils.error(ServiceReturnCodes.SYSTEM_EXCEPTION);
		}
	}
	/**
	 * 叶子类目分类器
	 * @Title: categoryClassifier   
	 * @Description: TODO 
	 * @param: @param categoryTreesBOs
	 * @param: @param categoryLeafBOs4BackendCatgeory      
	 * @return: void      
	 * @throws
	 */
	private void categoryClassifier(List<CategoryTreesBO> categoryTreesBOs,
			List<CategoryTreesBO> categoryLeafBOs4BackendCatgeory) {
		for (CategoryTreesBO categoryTreesBO : categoryTreesBOs) {
			if (categoryTreesBO.getCategoryIsLeaf() == 1) {
				if (categoryTreesBO.getRelatedType() == CategoryTreesRelatedType.BACKEND_CATEGORY_TYPE.getReleatedType()) {
					//获取后台类目列表
					categoryLeafBOs4BackendCatgeory.add(categoryTreesBO);
				} else if (categoryTreesBO.getRelatedType() == CategoryTreesRelatedType.VIRTUAL_CATEGORY_TYPE
						.getReleatedType()) {
						//TODO 虚拟类目添加到一个虚拟类目叶子列表中，用于后续处理
				} else if (categoryTreesBO.getRelatedType() == CategoryTreesRelatedType.LINK_CATEGORY_TYPE.getReleatedType()) {
					//TODO url连接类目添加到url叶子类目的列表中，用于后续处理
				}
			} else {
				//TODO 调用服务获取叶子类目，然后递归查询叶子节点，然后加入到相应的List中
			}
		}
	}
	
	@Override
	public List<SkuBO> getSkuByBackendCategoryList(List<CategoryTreesBO> categoryLeafBOs4BackendCatgeory, SkuRequestBO requestInfo) {
		//ProductRequestBO backendCategoryRequestBO = new ProductRequestBO();
		//TODO:按照约定，这里不会出现非叶子节点，以为前台类目只能挂靠到后台类目的叶子节点，但是为了严谨，还是需要递归查询叶子节点
		List<Long> backendCategoryList = new ArrayList<Long>();
		for (CategoryTreesBO categoryTreesBO : categoryLeafBOs4BackendCatgeory) {
			
			backendCategoryList.add(categoryTreesBO.getRelatedId());
		
		}
		Map<String, Object> criteriaMap = new HashMap<String, Object>(); 
		criteriaMap.put("categoryList", backendCategoryList);
		criteriaMap.put("companyID", requestInfo.getCompanyID());
		criteriaMap.put("sortType", requestInfo.getSortType());
		criteriaMap.put("sortOrder", requestInfo.getSortOrder());
		criteriaMap.put("startIndex", requestInfo.getStartPage()*requestInfo.getPageSize());
		criteriaMap.put("pageSize", requestInfo.getPageSize());
		List<SkuBO> skuList = productSkuMapper.getSkuByBackendCategoryList(criteriaMap);
		return skuList;
	}
	
	

	@Override
	public ProductSkuBo getSkuById(Long skuId) {
		ProductSku productSku = productSkuMapper.selectByPrimaryKey(skuId);
		return BeanUtils.newAndCopyProperties(ProductSkuBo.class, productSku);
	}

	@Override
	public List<ProductSkuBo> getSkuWithPriceBySkuIds(List<Long> skuIdList) {
		return productSkuMapper.getSkuWithPriceBySkuIds(skuIdList);
	}
	
	
	/**
	 * 根据店铺信息查询对应分类店铺内分组的sku列表
	 * 
	 * @param shopId
	 * @param pageNum
	 * @param pageSize
	 * @param sortType
	 * @param sortOrder
	 * @return
	 */
	public ServiceReturnInfo getSkuListByGroup(Long shopId, Long groupId, Integer pageNum, Integer pageSize,
			Integer sortType, Integer sortOrder){


		PageBo<ProductSkuBo> pageBo = new PageBo<ProductSkuBo>();

		ProductSkuExamplePaged skuExamplePaged = new ProductSkuExamplePaged();

		skuExamplePaged.setIsDeleted(DbConstants.IS_DELETED_FALSE);
		skuExamplePaged.setIsEnabled(DbConstants.TRUE);
		
		skuExamplePaged.setIsCanSale(DbConstants.TRUE);
		skuExamplePaged.setShopId(shopId); 
		skuExamplePaged.setSortOrder(sortOrder);
		skuExamplePaged.setSortType(sortType);
		
		if(groupId==null || groupId==GROUP_ALL){
			 //所有分组的sku
			 skuExamplePaged.setLayers(null); 
		}else{
			//当前分组对一个的层级串 (当前分组的所有子分组)
			ShopNavigationGroupBo groupBo = shopNavigationGroupInnerService.getShopNavGroupBoById(groupId);
			if(groupBo==null){
				skuExamplePaged.setLayers(null); 
			}else{
				String layers =groupBo.getLayers(); 
				skuExamplePaged.setLayers(layers );
			}
		}
	 
		int count = (int) productSkuMapper.countSkuListByGroup(skuExamplePaged);
		if (count > 0) {
			skuExamplePaged.setPageParam(PageParam.resetPageParam(pageNum, pageSize));
			List<ProductSkuBo> productSkuBoList = productSkuMapper
					.selectSkuListByByGroup(skuExamplePaged);
			 
			pageBo.setRows(productSkuBoList);
			pageBo.setTotal(count);
		}
		return ServiceReturnUtils.success(pageBo);
	
	}
	@Override
	public ServiceReturnInfo getSKUDetail(SkuRequestBO requestBO) {
		long skuID = requestBO.getSkuID();
		
		//首先从redis中获取
		String skuDetailInfo = CacheUtil.get(BaseProductConstant.SKU_DETAIL_REDIS_KEY+"_"+requestBO.getSkuID());
		if(!StringUtils.isEmpty(skuDetailInfo)) {
			return ServiceReturnUtils.success(skuDetailInfo);
		}
		
		ProductSkuExample example = new ProductSkuExample();
		
		com.xb.cloud.product.service.business.model.ProductSkuExample.Criteria criteria = example.createCriteria();
		criteria.andIdEqualTo(skuID);
		//criteria.andIsCanSaleEqualTo(DbConstants.PRODUCT_SKU_CAN_SALE);
		criteria.andIsEnabledEqualTo(DbConstants.PRODUCT_SKU_ENABLED);
		
		List<ProductSku> skuList = productSkuMapper.selectByExample(example);
		
		if(skuList.isEmpty()) {
			return ServiceReturnUtils.error(ServiceReturnCodes.SKU_NOT_EXIST_EXCEPTION);
		}
		ProductSku skuBO = skuList.get(0);
		
		//================开始创建ServiceReturnInfo=====================
		SkuDetailBO skuDetailBO = new SkuDetailBO();
		//设置sku详情主标题与副标题
		skuDetailBO.setName(skuBO.getSkuNameCn());
		skuDetailBO.setSubTitle(skuBO.getSkuTitleSub());
		
		//设置商家信息
		Long shopId = skuBO.getShopId();
		ShopBo shopBo = shopService.getById(shopId);
		if(shopBo != null) {
			ShopBo shopInfo = new ShopBo();
			shopInfo.setId(shopBo.getId());
			shopInfo.setShopLogoUrl(shopBo.getShopLogoUrl());
			shopInfo.setShopNameCn(shopBo.getShopNameCn());
			shopInfo.setShopAddress(shopBo.getShopAddress());
			shopInfo.setShopContacts(shopBo.getShopContacts());
			skuDetailBO.setShopBo(shopInfo);
		}
		
		//获取product信息
		ServiceReturnInfo  productReturnInfo = productService.getProductByID(skuBO.getProductId(), 1);
		if(ServiceReturnUtils.isError(productReturnInfo) || productReturnInfo.getData() == null) {
			return ServiceReturnUtils.error(ServiceReturnCodes.PRODUCT_NOT_EXIST_EXCEPTION);
		}
		ProductBo  productBo = (ProductBo) productReturnInfo.getData();
		//设置sku的规格
		skuDetailBO.setUnit(skuBO.getSkuUnit());
		skuDetailBO.setIsCanSale(skuBO.getIsCanSale()); 
		
		//设置sku详情轮播图片
		List<String> picList = productService.getProudctPicList(productBo.getId());
		skuDetailBO.setPictureURLList(picList);
		
		//获取product图文详细
		
		ServiceReturnInfo detailReturnInfo = productService.getProductDetailByID(skuBO.getProductId());
		
		if(ServiceReturnUtils.isSuccess(detailReturnInfo)) {
			ProductDescriptionBo descriptionBo = (ProductDescriptionBo) detailReturnInfo.getData();
			skuDetailBO.setProductDescription(descriptionBo.getDetailContent());
		}
		
		//获取商家发布sku的文字描述
		ProductSkuExtDescriptionExample descriptionExample = new ProductSkuExtDescriptionExample();
		com.xb.cloud.product.service.business.model.ProductSkuExtDescriptionExample.Criteria detailCriteria = descriptionExample.createCriteria();
		detailCriteria.andSkuIdEqualTo(skuID);
		List<ProductSkuExtDescription> skuExtendDetailList = productSkuExtDescriptionMapper.selectByExampleWithBLOBs(descriptionExample);
		if(!skuExtendDetailList.isEmpty()) {
			skuDetailBO.setSkuExtendDetail(skuExtendDetailList.get(0).getDetailContent());
		}
		
		//获取商家发布sku的上传图片描述
		
		ProductSkuExtPicExample extPicExample = new ProductSkuExtPicExample();
		com.xb.cloud.product.service.business.model.ProductSkuExtPicExample.Criteria extPicCriteria = extPicExample.createCriteria();
		extPicCriteria.andSkuIdEqualTo(skuID);
		List<ProductSkuExtPic> extPicDtoList = productSkuExtPicMapper.selectByExample(extPicExample);
		List<String> extPicList = new ArrayList<String>();
		for (ProductSkuExtPic productSkuExtPic : extPicDtoList) {
			extPicList.add(productSkuExtPic.getPicUrl());
		}
		skuDetailBO.setSkuExtendPicList(extPicList);
		//从mongo获取该sku对应product对应基本属性，如果是系列品包括系列属性
		long productKeyInMongo = productBo.getId();
		/**
		 * 1:如果是单品：mongo中存放的就是productid
		 * 2：如果是系列品，mongo中的key为系列品的主品（需主品）id，所以如果是系列子品（正常请求过来的都是子品），需要获取主品id
		 */
		Byte productType = productBo.getProductType();
		switch (productType) {
			case DbConstants.PRODUCT_TYPE_SINGLE:
				 break;
			case DbConstants.PRODUCT_TYPE_SERIAS_VIRTUAL:
				 break;
			case DbConstants.PRODUCT_TYPE_SERIAS_SUB:
				productKeyInMongo = productService.getMianProductIdBySubProjectId(productKeyInMongo);
			case DbConstants.PRODUCT_TYPE_COMBINATION:
				 break;
		
		}
		
		ServiceReturnInfo productMongoInfo = productMongoService.findById(productKeyInMongo);
		if(ServiceReturnUtils.isError(productMongoInfo) || productMongoInfo.getData() == null) {
			return ServiceReturnUtils.error(ServiceReturnCodes.SKU_MONGO_NOT_EXIST_EXCEPTION);
		}
		skuDetailBO.setSkuID(skuID);
		
		ProductMongoBo productMongoBO = (ProductMongoBo)productMongoInfo.getData();
		//标识该sku是系列品还是单品
		skuDetailBO.setSkuType(productMongoBO.getProductType());
		//设置基本属性
		skuDetailBO.setBaseAttrs(productMongoBO.getBaseAttrs());
		//设置系列属性
		skuDetailBO.setSeriesAttrs(productMongoBO.getSeriesAttrs());
		
		
		if(productMongoBO.getProductType() == DbConstants.PRODUCT_TYPE_SERIAS_VIRTUAL) {
			String skuMongoKey = productKeyInMongo + DbConstants.KEY_SEGMENTATION + shopId; 
			ServiceReturnInfo skuMongoInfo = productMongoService.findByProductShopId(skuMongoKey);
			if(ServiceReturnUtils.isError(skuMongoInfo) || skuMongoInfo.getData() == null) {
				return ServiceReturnUtils.error(ServiceReturnCodes.SKU_MONGO_NOT_EXIST_EXCEPTION);
				
			}
			ProductShopSeriesMongoBo skuMongoBO = (ProductShopSeriesMongoBo) skuMongoInfo.getData();
			skuDetailBO.setSeriesAttributeCombSkuIdMap(skuMongoBO.getSeriesAttributeCombSkuIdMap());
		}
		
		
		
		//================结束创建ServiceReturnInfo=====================
		
		return ServiceReturnUtils.success(skuDetailBO);
	}


	@Override
	public ServiceReturnInfo getSKUPrice(SkuRequestBO requestBO) {
		ProductSkuPriceBo bo =  getSKUPriceBySkuId(requestBO.getSkuID());
		if(null == bo) {
			return ServiceReturnUtils.error(ServiceReturnCodes.PRODUCT_PRICE_NOT_EXIST_EXCEPTION);
		} else {
			return ServiceReturnUtils.success(bo);
		}
		
	}
	private ProductSkuPriceBo getSKUPriceBySkuId(long skuId) {
		ProductSkuPriceExample example = new ProductSkuPriceExample();
		com.xb.cloud.product.service.business.model.ProductSkuPriceExample.Criteria criteria = example.createCriteria();
		criteria.andSkuIdEqualTo(skuId);
		criteria.andIsEnabledEqualTo(DbConstants.PRODUCT_SKU_ENABLED);
		criteria.andIsDeletedEqualTo(DbConstants.IS_DELETED_FALSE);
		List<ProductSkuPrice> priceList = productSkuPriceMapper.selectByExample(example);
		if (!priceList.isEmpty()) {
			ProductSkuPrice productSkuPrice = priceList.get(0);
			ProductSkuPriceBo bo = new ProductSkuPriceBo();
			bo.setPriceSale(productSkuPrice.getPriceSale());
			bo.setPriceMarket(productSkuPrice.getPriceMarket());
			bo.setShowOriginalPrice(productSkuPrice.isShowOriginalPrice());
			return bo;
		}
		return null;
		
	}


	@Override
	public ServiceReturnInfo getGroupSkuCount(Long shopId, Long groupId) {

		ProductSkuExamplePaged skuExamplePaged = new ProductSkuExamplePaged();
		skuExamplePaged.setShopId(shopId);
		skuExamplePaged.setIsDeleted(DbConstants.IS_DELETED_FALSE);
		skuExamplePaged.setIsEnabled(DbConstants.TRUE);
		skuExamplePaged.setIsCanSale(DbConstants.TRUE);

		if (groupId == null || groupId == GROUP_ALL) {
			// 所有分组的sku
			skuExamplePaged.setLayers(null);
		} else {
			// 当前分组对一个的层级串 (当前分组的所有子分组)
			ShopNavigationGroupBo groupBo = shopNavigationGroupInnerService.getShopNavGroupBoById(groupId);
			if (groupBo == null) {
				skuExamplePaged.setLayers(null);
			} else {
				String layers = groupBo.getLayers();
				skuExamplePaged.setLayers(layers);
			}
		}

		int count = (int) productSkuMapper.countSkuListByGroup(skuExamplePaged);

		return ServiceReturnUtils.success(count);
	}
}
